import store from "@/stores/index.js"

// 不需要验证登录跳转
export const openPage = (url = '', params = {}) => open({ url, params })

// 需要验证登录跳转
export function authOpenPage(url, params) {
	console.log('验证跳转', store().user.token)
	if (!store().user.token) return open({ url: "/pages/account/login" })
	open({ url, params })
}

// 登录跳转
export function openlogin(){
	open({ url: "/pages/account/login" })
}

// 共有跳转
function open({ url, params }) {
	if (!url) return uni.showToast({ title: "页面不存在", icon: "error" })
	let path = `${url}?${objectToUri(params)}`
	uni.navigateTo({ url: path })
}


/**
 * @param {String} path 页面路径
 * @param {Object} params 携带的参数
 * @param {Boolean} isAuth 是否验证登录 默认true
 * @param {Boolean} isReplace 是否替换当前页面
 * @param {Function} onSuccess 打开成功回调
 * @param {Object} events 事件
 */
export function navigate(path, { params = {}, isAuth = true, isReplace = false, events = {}, onSuccess = () => {} } = {}) {
	let url
	if (isAuth && !store().user.isLogin) url = "/pages/account/login"
	else url = `${path}?${objectToUri(params)}`
	
	if (isReplace) uni.redirectTo({ url })
	else uni.navigateTo({ url, events, success: onSuccess })
}

/**
 * @param {Number} layer 返回的层级 
 */
export const navigateBack = (layer = 1) => uni.navigateBack({ delta: layer })

function objectToUri(params) {
	let temp = ""
	params && Object.keys(params).forEach((key, index) => temp += `&${key}=${params[key]}`)
	return temp
}
